#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/errno.h>


int creation_result;
int join_result;
int detach_result;
char bufor[BUFSIZ];


/**
* This function print a message to the stdout
*
*/
void showErrorAndTerminate(char tekst[])
{
	printf("ERROR : %s !!!",tekst);
	exit(-1);
}


/**
* the thread can terminate in 3 different ways
* - the main program calls pthread_cancel
* - function pthread_exit() is called explicitely from within the thread
* - myroutine returns => implicit call to pthread_exit()
*/
void *myroutine()
{
	printf("[thread] I am a thread of the program.\n");
/* BUFSIZ is defined in a standard library 
checkout here: http://ieng9.ucsd.edu/~cs30x/Std.C/stdio.html
*/

	//reading from standard input	
	printf("What's your name : ");
	fgets(bufor,BUFSIZ,stdin);    
	return bufor;
	
//exiting the thread (JE ME DEMANDE SI CETTE LIGNE EST ATTEINTE)
	printf("before explicit call to pthread_exit() \n");
	pthread_exit(0);
}//myroutine

int main(){

	pthread_t thread_handle;//this is a buffer for the thread handle
	//1. ready to create a thread
	printf("[system] calling the function PTHREAD_CREATE ...\n");
	creation_result = pthread_create(&thread_handle,NULL,myroutine,NULL);
	if (creation_result != 0) showErrorAndTerminate("PORAZKA\n");

	//2. we're going to join the thread: we wait for the thread to terminate...
	printf("[system] Joining a thread ...\n");    
	join_result = pthread_join(thread_handle,NULL);
	if (join_result != 0) showErrorAndTerminate("ERROR\n");

	//3. Reaching here means the thread has terminated: we show data collected by child thread
	printf("[program] I received the data ... %s\n",bufor);

	//4. Detaching from the thread (JE ME DEMANDE SI CA VA CAR THREAD DEJA FINI...)
	//EN PLUS ON NE 
	printf("[system] Detaching from the thread...\n");
	detach_result = pthread_detach(thread_handle);
	if (detach_result != 0) showErrorAndTerminate("PORAZKA\n");

	//5. Exiting...
	printf("[Program] Ready to exit...\n");
	exit(0);

}//main
